using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Systems.Workflow;
using Deepcode.Flux.Core.Systems.Workflow.Bases;
using Deepcode.Flux.Core.Services.Security;

public partial class Menu_Taskpads_workflow : System.Web.UI.UserControl
{
	#region Page_Load
	/// <summary>
	/// Page loading logic - bind data to the grid
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		// Must rebind each time otherwise the linkbuttons will disappear between postbacks
		BindTasks();
	}
	/// <summary>
	/// Page init logic - capture each item being bound to the grid
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Init(object sender, EventArgs e)
	{
		datagrid.ItemDataBound += new DataGridItemEventHandler(datagrid_ItemDataBound);
		datagrid.ItemCommand += new DataGridCommandEventHandler(datagrid_ItemCommand);
	}
	#endregion
	#region Tasks grid
	/// <summary>
	/// Binds data to the tasks grid
	/// </summary>
	protected void BindTasks()
	{
		AdministrationSecuritySession sess = AdministrationSecurity.GetSession();
		if (sess == null) return;

		datagrid.DataSource = new Tasks().GetOperatorTasks(sess.PK_ID, sess.GroupsCSV);
		datagrid.DataBind();
	}
	/// <summary>
	/// As each item is bound to the grid, process it's options
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void datagrid_ItemDataBound(object sender, DataGridItemEventArgs e)
	{
		if ((e.Item.ItemType != ListItemType.AlternatingItem) &&
			(e.Item.ItemType != ListItemType.Item) &&
			(e.Item.ItemType != ListItemType.SelectedItem)) return;

		// Get the placeholder
		PlaceHolder host = (PlaceHolder) e.Item.FindControl("linkbuttons");
		if (host == null) return;
		
		// Get the task
		Task t = (Task) e.Item.DataItem;
		if (t == null) return;

		// Create an engine object based on the task
		WorkflowEngine Engine = new WorkflowEngine( t.HandlerCodeID );
		if (Engine == null) return;
		
		// Get a copy of the process
		Process p = t.ParentProcess;
		if (p == null) return;

		// Work out if we can view or edit
		// Do data edit link
		bool bHasEditLink = false;
		if (p.DataCanEdit)
		{
			string EditURL = Engine.GetEditURL( t );
			if (EditURL != "")
			{
				HyperLink h = new HyperLink();
				h.CssClass = "SafeLink";
				h.Text = "[Edit]";
				h.NavigateUrl = EditURL;
				host.Controls.Add(h);
				bHasEditLink = true;
			}
		}
		
		// Do data view link if can't be edited
		if (p.DataCanView && (!bHasEditLink))
		{
			string ViewURL = Engine.GetViewURL(t);
			if (ViewURL != "")
			{
				HyperLink h = new HyperLink();
				h.CssClass = "SafeLink";
				h.Text = "[View]";
				h.NavigateUrl = ViewURL;
				host.Controls.Add(h);
			}
		}

		// Get the Exit Paths available
		foreach (TaskExitPath path in t.ExitPaths)
		{
			if( AdministrationSecurity.IsMemberOfOneGroupID( path.CSV_AllowedGroups ))
			{
				// Create a link button with the taskID and exitPathID - unless it's a UI
				if (path.uiTaskMethod != "")
				{
					HyperLink h = new HyperLink();
					h.CssClass = "SafeLink";
					h.Text = "[" + path.Caption + "]";
					h.NavigateUrl = Engine.GetExitUI(path.uiTaskMethod, t.PK_ID, path.PK_ID);
					host.Controls.Add(h);
				}
				else
				{
					LinkButton lb = new LinkButton();
					lb.Text = "[" + path.Caption + "]";
					lb.CssClass = "SafeLink";
					lb.CommandName = "ProcessExitPath";
					lb.CommandArgument = String.Format("{0},{1}", t.PK_ID, path.PK_ID);
					host.Controls.Add(lb);
				}
			}
		}
	}
	/// <summary>
	/// Process any grid commands
	/// </summary>
	/// <param name="source"></param>
	/// <param name="e"></param>
	protected void datagrid_ItemCommand(object source, DataGridCommandEventArgs e)
	{
		if (e.CommandName == "ProcessExitPath")
		{
			// Ensure it's a string argument
			if (!(e.CommandArgument is string)) return;
			string Arguments = (string)e.CommandArgument;
			// Ensure it contains data
			if (Arguments == "") return;
			// Split it into Task/ExitPath ID's
			string[] Args = Arguments.Split(',');
			// Ensure there are two and only two
			if (Args.Length != 2) return;
			// Convert to ID's
			int TaskID = -1;
			int ExitPathID = -1;
			try
			{
				TaskID = Int32.Parse(Args[0]);
				ExitPathID = Int32.Parse(Args[1]);
			}
			catch { return; }
			
			// Load the task and exit path
			Task			task = new Tasks().GetTasksByID( TaskID );
			TaskExitPath	exitpath = new TaskExitPaths().GetTaskExitPathByID( ExitPathID );
			// Ensure it's all valid
			if( (task==null) || (exitpath==null)) return;
			// Process it
			WorkflowEngine engine = new WorkflowEngine( task.HandlerCodeID );
			if (engine == null) return;
			engine.ProcessExitAction( TaskID, ExitPathID );
			// Rebind the data
			BindTasks();
		}
	}
	#endregion
}
